import { _decorator, Component, Node, Prefab, instantiate, Vec3, view, math, Vec2, RigidBody2D, UIOpacity, tween, NodePool } from 'cc';
import { BulletType, ItemType, GameEventType } from '../Event/EnumDefine';
import { EventManager } from '../Event/EventManager';
import { Bullet } from './Bullet';
import { BuffDataType, DataConfig } from '../Config/DataConfig';
import Common from '../Config/Common';
const { ccclass, property } = _decorator;

@ccclass('ShootBomb')
export class ShootBomb extends Component {
    @property(Node)
    bulletParentNode: Node = null!; //添加子弹的父节点

    @property(Prefab)
    bulletPrefab: Prefab = null!;  // 子弹预制体

    shootSpeed: number = 25; // 子弹发射速度（像素/秒）
    shootInterval: number = 3; // 发射间隔时间（秒）
    damage: number = 10; //子弹伤害

    private iconId: number = 0;
    private bulletType = BulletType.Bomb; //当前子弹类型
    private bulletNum: number = 1; //子弹数量

    private bulletPool: NodePool = new NodePool();

    protected start(): void {
        this.initPool();
    }

    initPool() {
        this.bulletPool.clear();
        for (let i = 0; i < 10; i++) {
            this.bulletPool.put(instantiate(this.bulletPrefab));
        }
    }

    getBulletNode() {
        if (this.bulletPool.size() === 0) {
            this.bulletPool.put(instantiate(this.bulletPrefab));
        }
        return this.bulletPool.get();
    }

    removeBulletNode(bulletNode: Node) {
        bulletNode.removeFromParent();
        let bullet = bulletNode.getComponent(Bullet);
        if (bullet) {
            bullet.destroy();
        }
        this.bulletPool.put(bulletNode);
    }

    /** 开始发射子弹 */
    startShoot(params: { itemType: ItemType, buffData: BuffDataType }) {
        if (params?.buffData?.iconId) {
            this.iconId = params.buffData.iconId;
        }
        if (params?.buffData?.bulletNum) {
            this.bulletNum = params?.buffData?.bulletNum;
        }
        if (params?.buffData?.shootSpeed) {
            this.shootSpeed = params.buffData.shootSpeed;
        }
        if (params?.buffData?.addAttackValue) {
            this.damage += params.buffData.addAttackValue;
        }
        this.unschedule(this.shootBombBullets)
        this.schedule(this.shootBombBullets, this.shootInterval);
    }

    /** 停止发射 */
    stopShoot() {
        this.unschedule(this.shootBombBullets);
    }

    /** 发射引发爆炸的道具子弹 */
    shootBombBullets() {
        for (let i = 0; i < this.bulletNum; i++) {
            this.scheduleOnce(() => {
                EventManager.instance.triggerEvent(GameEventType.Player_Scale_Effect, null);
                let angle = math.randomRange(-30, 30);
                let pos = this.node.position.clone();
                this.createBullet(this.bulletType, angle, pos)
            }, i * 0.01)
        }
    }

    createBullet(type: BulletType, angle: number, pos: Vec3) {
        const bullet = this.getBulletNode();
        const childTuowei = bullet.getChildByName('tuowei');
        childTuowei.children.forEach((icon) => {
            icon.active = Number(icon.name) == this.iconId;
        });
        const childPoint = bullet.getChildByName('point');
        childPoint.children.forEach((icon) => {
            icon.active = Number(icon.name) == this.iconId;
        });
        bullet.setParent(this.bulletParentNode)
        // 子弹出现效果
        let uiOpacity = bullet.getComponent(UIOpacity);
        uiOpacity.opacity = 0;
        tween(uiOpacity)
            .to(0.1, { opacity: 255 }) // 透明度从 0 渐变到 255
            .start();

        // 设置子弹位置
        bullet.setPosition(pos);
        bullet.angle = -angle;
        // 计算子弹的方向向量
        const radians = angle * Math.PI / 180;
        const direction = new Vec2(Math.sin(radians), Math.cos(radians)).normalize();

        // 初始化子弹配置数据
        const bulletComponent = bullet.addComponent(Bullet);
        bulletComponent.type = type;
        bulletComponent.shootSpeed = this.shootSpeed;
        bulletComponent.damage = this.damage;
        bulletComponent.set_cb_removeBullet((bulletNode: Node)=>{
            this.removeBulletNode(bulletNode);
        });

        // 设置子弹的速度
        const rigidBody = bullet.getComponent(RigidBody2D);
        if (rigidBody) {
            rigidBody.linearVelocity = direction.multiplyScalar(this.shootSpeed);
        }
        return bullet;
    }

    // 检测子弹是否超出屏幕范围
    isBulletOutOfScreen(bullet: Node): boolean {
        const screenSize = Common.instance.getScreenSize();
        const bulletPos = bullet.position;

        // 判断子弹是否超出屏幕范围
        return (
            bulletPos.x < -screenSize.width / 2 ||
            bulletPos.x > screenSize.width / 2 ||
            bulletPos.y < -screenSize.height / 2 ||
            bulletPos.y > screenSize.height / 2
        );
    }
}
